package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService {


    @Autowired
    private VMService vmService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer producer;

    /**
     * 完成工单
     * @param taskId
     * @return
     */
    @Override
    public boolean complete(Long taskId) {
        TaskEntity task = getById(taskId);
        if(task.getTaskStatus()!=VMSystem.TASK_STATUS_PROGRESS){
            throw new LogicException("工单状态不是进行中");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        updateById(task);

        if(task.getProductTypeId().equals(VMSystem.TASK_TYPE_DEPLOY) ||
            task.getProductTypeId().equals(VMSystem.TASK_TYPE_REVOKE)) {   // 如果是投放工单或者撤机工单
            noticeVMServiceStatus(task);
        }

        if(task.getProductTypeId().equals(VMSystem.TASK_TYPE_SUPPLY)){   // 如果是补货工单
            noticeVMServiceSupply(task);
        }

        return true ;
    }

    /**
     * 获取同一天内分配的工单最少的人
     *
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return  id
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002"; // 补货工单
        if(isRepair){      // 维修工单
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                +LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+regionId+"."+roleCode;
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 1);
        if(range==null || range.isEmpty()){
            throw new LogicException("该区域暂时没有相关人员");
        }
        return (int) range.stream().collect(Collectors.toList()).get(0);
    }

    private void noticeVMServiceSupply(TaskEntity task) {
        QueryWrapper<TaskDetailsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TaskDetailsEntity::getTaskId,task.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(queryWrapper); // 查询该设备的补货后的详情

        SupplyContract contract = new SupplyContract();   // 创建协议对象
        contract.setInnerCode(task.getInnerCode());       // 设置售货机编码
        List<SupplyChannel> list = Lists.newArrayList();
        details.forEach(item -> {         //  遍历补货后详情
            SupplyChannel supplyChannel = new SupplyChannel();
            supplyChannel.setChannelId(item.getChannelCode());   // 设置货道编号
            supplyChannel.setCapacity(item.getExpectCapacity()); // 设置补货数量
            list.add(supplyChannel);
        });
        contract.setSupplyData(list);
        try {
            producer.send(TopicConfig.VMS_SUPPLY_TOPIC,2,contract);    // 发送协议
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void noticeVMServiceStatus(TaskEntity task) {
        var taskCompleteContract = new TaskCompleteContract();
        taskCompleteContract.setInnerCode(task.getInnerCode());
        taskCompleteContract.setTaskType(task.getProductTypeId());
        try {
            producer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,taskCompleteContract);
        }catch (Exception e){
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }


    @Override
    public boolean cancel(Long taskId, CancelTaskViewModel des) {
        TaskEntity task = getById(taskId);
        if(task.getTaskStatus().equals(VMSystem.TASK_STATUS_FINISH)
                || task.getTaskStatus().equals(VMSystem.TASK_STATUS_CANCEL)){
            throw  new LogicException("工单已完成或者已经取消");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        task.setDesc(des.getDesc());
        updateTaskZSet(task,-1);
        return updateById(task);
    }

    @Autowired
    private TaskDetailsService taskDetailsService;

    /**
     * 创建工单
     *
     * @param model
     * @return
     */
    @Transactional
    @Override
    public boolean create(TaskViewModel model) {
        // 判断参数是否为空
        if (model == null) return false;
        // 检查状态是否正常
        checkCreateTask(model.getInnerCode(), model.getProductType());

        if (hasTask(model.getInnerCode(), model.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        TaskEntity task = new TaskEntity();
        task.setTaskCode(generateTaskCode());
        BeanUtils.copyProperties(model, task);
        UserVO user = userService.getUser(model.getUserId());
        task.setUserName(user.getUserName());
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        task.setProductTypeId(model.getProductType());
        VmVO info = vmService.getVMInfo(task.getInnerCode());
        task.setAddr(info.getNodeAddr());
        task.setRegionId(info.getRegionId());
        save(task);

        if (model.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            model.getDetails().stream().forEach(temp -> {
                TaskDetailsEntity viewModel = new TaskDetailsEntity();
                BeanUtils.copyProperties(temp, viewModel);
                viewModel.setTaskId(task.getTaskId());
                taskDetailsService.save(viewModel);
            });
        }
        updateTaskZSet(task,1);

        return true;
    }

    private void updateTaskZSet(TaskEntity task,int score){
        String roleCode="1003";// 运维员
        if(task.getProductTypeId() ==2 ){  //如果是补货工单
            roleCode = "1002";   // 运营员
        }
        String key=VMSystem.REGION_TASK_KEY_PREF+LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+task.getRegionId()+"."+roleCode;
        redisTemplate.opsForZSet().incrementScore(key,task.getUserId(),score);

    }

    @Override
    public boolean accept(Long taskId) {
        TaskEntity task = getById(taskId);
        if(task.getTaskStatus()!=VMSystem.TASK_STATUS_CREATE){
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS); // 修改工单状态为进行中

        return updateById(task);
    }

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime,LocalDate.parse(start,DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE).plusDays(1));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }

    private void checkCreateTask(String innerCode, int productType) {
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if (vmInfo == null) {
            throw new LogicException("该售货机不存在");
        }
        // 如果是投放工单 并且，设备状态是运行中
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运行");
        }

        //补货订单，设备不在运行
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运行状态");
        }
        // 撤机工单，设备不在运行
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运行状态");
        }
    }

    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    private boolean hasTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> wq = new QueryWrapper<>();
        wq.lambda().select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return count(wq) > 0;
    }
}